package com.jubaozan.c3.framework.logs;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;


import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/7 18:09
 */

@Slf4j

public class UtilJson {
  private static final ObjectMapper DEFAULT_MAPPER;

  static {
    ObjectMapper mapper = init(new ObjectMapper());
    mapper.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM);
    DEFAULT_MAPPER = mapper;
  }

  private UtilJson() {}

  /** 基本配置初始化(允许name双引号单引号无引号, 不输出null值，而content.includeAlways), 遇到unknown属性不fail */
  private static ObjectMapper init(ObjectMapper mapper) {
    mapper.enable(Feature.ALLOW_SINGLE_QUOTES, Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 不知道的属性，不异常
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // 禁用empty bean时异常
    try {
      mapper.setDefaultPropertyInclusion(Include.NON_NULL);
    } catch (NoSuchMethodError e) {
      mapper.setSerializationInclusion(Include.NON_NULL);
    }
    return mapper;
  }

  public static void writeEvent(OutputStream out, Map<String, Object> map) throws IOException {
    JsonGenerator gen = DEFAULT_MAPPER.getFactory().createGenerator(out);
    gen.writeObject(map);
    gen.flush();
  }

  public static void writeEvent(Writer writer, Map<String, Object> map) throws IOException {
    JsonGenerator gen = DEFAULT_MAPPER.getFactory().createGenerator(writer);
    gen.writeObject(map);
    gen.flush();
  }

  @SuppressWarnings("unchecked")
  public static Map<String, Object> toMap(String json) {
    try {
      return DEFAULT_MAPPER.readValue(json, Map.class);
    } catch (IOException e) {
      throw new IllegalArgumentException("json=" + json, e);
    }
  }

}
